//LCR 107. 01 矩阵
class Solution {
    int m, n;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    typedef pair<int, int> PII;

public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        m = mat.size();
        n = mat[0].size();
        vector<vector<int>> ret(m, vector<int>(n, -1));
        queue<PII> q;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (mat[i][j] == 0) {
                    q.push({i, j});
                    ret[i][j] = 0;
                }
        while (q.size()) {
            auto [a, b] = q.front();
            q.pop();
            for (int i = 0; i < 4; i++) {
                int x = a + dx[i];
                int y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && ret[x][y] == -1) {
                    ret[x][y] = ret[a][b] + 1;
                    q.push({x, y});
                }
            }
        }
        return ret;
    }
};


//飞地的数量
class Solution {
public:
    int m, n;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    typedef pair<int, int> PII;
    int numEnclaves(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        vector<vector<bool>> vis(m, vector<bool>(n));
        int ret = 0;
        queue<PII> q;
        for (int i = 0; i < m; i++) {
            if (grid[i][0]) {
                q.push({i, 0});
                vis[i][0] = true;
            }
            if (grid[i][n - 1]) {
                q.push({i, n - 1});
                vis[i][n - 1] = true;
            }
        }
        for (int j = 0; j < n; j++) {
            if (grid[0][j]) {
                q.push({0, j});
                vis[0][j] = true;
            }
            if (grid[m - 1][j]) {
                q.push({m - 1, j});
                vis[m - 1][j] = true;
            }
        }
        /*  for (int i = 0; i < m; i++) {
              for (int j = 0; j < n; j++)
                  cout << i << '-' << j << vis[i][j];
              cout << endl;
          }*/
        while (q.size()) {
            auto [a, b] = q.front();
            q.pop();
            for (int i = 0; i < 4; i++) {
                int x = a + dx[i];
                int y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] &&
                    !vis[x][y]) {
                    q.push({x, y});
                    vis[x][y] = true;
                }
            }
        }
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] && !vis[i][j])
                    ret++;
        return ret;
    }
};